{% extends 'base.html' %}

{% block cssdefine %}
    <link rel="stylesheet" href="{{ url_for('static', filename='css/railscasts.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/jquery.contextmenu.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/zTreeStyle.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='codemirror/codemirror.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='codemirror/codemirror.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='codemirror/theme/idea.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='codemirror/theme/monokai.css') }}">
{% endblock %}

{% block jsdefinebefore %}
    <script type="text/javascript" src="{{ url_for('static', filename='js/marked.min.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='js/highlight.pack.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='js/jquery.contextmenu.min.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='js/jquery.ztree.core.min.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='js/jquery.ztree.exedit.min.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='js/idea-note.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='codemirror/codemirror.min.js') }}"></script>
    <script type="text/javascript"
            src="{{ url_for('static', filename='codemirror/mode/markdown-mode.min.js') }}"></script>
    <script type="text/javascript" src="{{ url_for('static', filename='codemirror/addone/closetag.js') }}"></script>

    <script>
        hljs.tabReplace = ' ';
        hljs.initHighlightingOnLoad();
    </script>
{% endblock %}



{% block centerframe %}
    <textarea id="editor" placeholder="写你想写" spellcheck="false" hidden></textarea>
{% endblock %}


{% block jsdefineafter %}
    <script type="text/javascript">
        $(document).ready(function () {

            catalogTree = $("#catalog-tree");
            previewer = $(".preview");


            editor = CodeMirror.fromTextArea(document.getElementById("editor"), {
                theme: 'idea monokai',
                extraKeys: {"Ctrl": "autocomplete"},//ctrl可以弹出选择项
                lineNumbers: true,//显示行号
                autoCloseTags: true,
                autofocus: true,
                value: "写你想写",
                matchBrackets: true,
                tabSize: 4,
                indentUnit: 4,
                smartIndent: true,
                spellcheck: false,
                lineSeparator: ""
            });


            preview = function (content) {
                content = content.replace(/\n\n/g, "\n<br>");
                previewer.html(
                    marked(content, {
                        highlight: function (code) {
                            return hljs.highlightAuto(code).value;
                        },
                        pedantic: false,
                        gfm: true,
                        tables: true,
                        breaks: true,
                        sanitize: false,
                        smartLists: true,
                        smartypants: false,
                        xhtml: false,
                        headerIds: true,
                        langPrefix: 'hljs ',
                        //baseUrl: 'http://localhost:5555/'
                    })
                );
            };

            catalogTree.catalog({
                treeDataUrl: "{{ url_for('core.fetch_notes') }}",
                renameUrl: "{{ url_for('core.update_note', type='rename') }}",
                flashFunc: flashMessage,
                nodeContent: "{{ url_for('core.fetch_content') }}",
                previewFunc: preview,
                editor: editor
            });


            $.bindTreePopu({
                nodeSeletor: "a[class^='level']",
                syncUrl: "{{ url_for('core.sync', method='sync') }}",
                dropUrl: "{{ url_for('core.drop_note') }}",
                addChildUrl: "{{ url_for('core.add_note') }}",
                flashFunc: flashMessage
            });


            // 保存数据
            editor.on("change", function () {
                node = $.zTreeObj.getSelectedNodes()[0];
                content = editor.getValue();
                $.ajax({
                    url: "{{ url_for('core.update_note', type='content') }}",
                    type: "post",
                    data: {
                        id: node.id,
                        content: content,
                    },
                    success: function () {
                        preview(content);
                    },
                    error: function () {
                        flashMessage("保存失败", true);
                    }
                })
            });

            // 同步滚动窗口
            editor.on('scroll', function () {
                scrollRate = editor.getScrollInfo().top / editor.getScrollInfo().height;
                previewer[0].scrollTop = (previewer[0].scrollHeight) * scrollRate;
            });

            // 粘贴图片
            editor.on('paste', function (editor, e) {
                if (typeof e.clipboardData === "object") {
                    items = e.clipboardData.items || e.clipboardData.files || [];

                    $.each(items, function (index, item) {
                        if (item.kind === "file" && item.type.match(/^image/).length > 0) {
                            formData = new FormData();
                            image = item.getAsFile();
                            if (image === null){
                                flashMessage("剪切板中不存在图片",true);
                                return
                            }
                            formData.append('image', item.getAsFile());
                            formData.append('id', zTreeObj.getSelectedNodes()[0].id);

                            $.ajax({
                                url: "{{ url_for('core.upload_image') }}",
                                type: 'POST',
                                cache: false,
                                data: formData,
                                processData: false,
                                contentType: false,
                                dataType: 'json',
                                success: function (result) {
                                    mdUrl = "![image](url)".replace("url", result['filename']);
                                    editor.replaceSelection(mdUrl)
                                },
                                error: function () {
                                    flashMessage("图片保存失败", true)
                                }
                            })
                        }
                    });
                }

            });

            // 快捷键
            document.addEventListener('keydown', function () {
                if (event.keyCode === 27) {
                    // esc 返回只读模式
                    splitter2.position("0%");
                    event.preventDefault();
                } else if (event.ctrlKey && event.keyCode === 83) {
                    // ctrl+s pull&&push
                    $.syncNote();
                    event.preventDefault();
                } else if (event.ctrlKey && event.keyCode === 73) {
                    // ctrl+i 进入编辑模式
                    splitter2.position("50%");
                    editor.refresh();
                    event.preventDefault();
                } else if (event.shiftKey && event.keyCode === 83) {
                    // shift+s 切换侧边栏(目录树)
                    if (splitter1.position() > 15) {
                        splitter1.position("0%")
                    } else {
                        splitter1.position("15%");
                    }
                    event.preventDefault();
                } else if (event.ctrlKey && event.shiftKey && event.keyCode === 70) {
                    // ctrl+shift+f //全屏编辑+预览
                    splitter1.position("0%");
                    splitter2.position("60%");
                    event.preventDefault();
                }
            });

        });
    </script>
{% endblock %}